<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主要内容区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row class="el-bottom">
        <el-col :span="6">
          <el-button type="primary" @click="AddRoleDialog()"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格内容 -->
      <el-table :data="rolesList" stripe border>
        <!-- 首列扩展区 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!--一级权限区域 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['row_center', 'bg_bottom', i1 == 0 ? 'bg_top' : '']"
            >
              <el-col :span="5" class="col_center">
                <!-- 一级权限标签 -->
                <el-tag @close="removeRolePower(scope.row, item1.id)">
                  {{ item1.authName }}</el-tag
                >
                <!-- 小箭头 -->
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限区域 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 == 0 ? '' : 'bg_top', 'row_center']"
                >
                  <el-col :span="6">
                    <!-- 二级权限标签 -->
                    <el-tag
                      type="success"
                      @close="removeRolePower(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <!-- 小箭头 -->
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限区域 -->
                  <el-col :span="18">
                    <!-- 三级权限标签 -->
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRolePower(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <!-- 操作区 -->
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="EditRoleBtn(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="DeleteRoleBtn(scope.row.id)"
            >
              删除
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="getSettingTreeBtn(scope.row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SettingDialogVisible"
      width="50%"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="SettingDefaultProps"
        show-checkbox
        :default-expand-all="true"
        node-key="id"
      ></el-tree>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="SettingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="SettingDialogVisible = false">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="this.AddRoleVisible"
      :before-close="AddRoleDialogClose"
      width="50%"
    >
      <el-form :model="AddRolesList">
        <el-form-item label="角色名称" prop="roleName" required>
          <el-input v-model="AddRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDescribe">
          <el-input v-model="AddRolesList.roleDescribe"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="this.EditRoleVisible"
      :before-close="EditRoleDialogClose"
      width="50%"
    >
      <el-form :model="EditRolesList">
        <el-form-item label="角色名称" prop="roleName" required>
          <el-input v-model="EditRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="EditRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditRole(EditRolesList.roleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 分配权限对话框显示或隐藏
      SettingDialogVisible: false,
      // 权限列表
      rightsList: [],
      // 树形结构需要绑定的参数对象
      SettingDefaultProps: {
        children: "children",
        label: "authName",
      },
      // 默认要勾选的Key的数组
      defKey: [],
      // 显示或隐藏添加角色对话框
      AddRoleVisible: false,
      // 添加角色数据
      AddRolesList: {
        roleName: "",
        roleDescribe: "",
      },
      // 显示或隐藏编辑角色对话框
      EditRoleVisible: false,
      // 编辑角色数据
      EditRolesList: {},
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取权限列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        this.$message.error("获取角色数据失败！");
      } else {
        this.rolesList = res.data;
      }
    },
    // 删除当前角色的权限
    async removeRolePower(role, rightid) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        this.$message.info("已取消删除权限");
      } else {
        console.log("确认删除");
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightid}`
        );
        if (res.meta.status !== 200) {
          this.$message.error("删除权限失败!");
        } else {
          // 返回值是当前角色最新的权限，直接赋值给rele就不用刷新页面
          role.children = res.data;
          this.$message.success("删除权限成功!");
        }
      }
    },
    // 点击分配权限按钮功能
    async getSettingTreeBtn(role) {
      // 获取权限列表/tree
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        this.$message.error("获取权限列表失败!");
      } else {
        this.rightsList = res.data;
      }
      // this.getLeafKeys(role, this.defKey);
      // 显示对话框
      this.SettingDialogVisible = true;
    },
    // 通过递归方式获取树形控件默认选中的权限
    // getLeafKeys(node, arr) {
    //   // 如果当前 node 节点不包含 children 属性，则是三级节点
    //   if (!node.children) {
    //     return arr.push(node.id);
    //   }

    //   node.children.forEach((item) => this.getLeafKeys(item, arr));
    // },
    // 添加角色按钮触发事件
    AddRoleDialog() {
      this.AddRoleVisible = true;
    },
    // 添加角色确认按钮触发事件
    async AddRole() {
      const { data: res } = await this.$http.post("roles", this.AddRolesList);
      if (res.meta.status !== 201) {
        this.$message.error("添加角色失败！");
      } else {
        this.$message.success("添加角色成功！");
      }
      this.getRolesList();
      this.AddRoleVisible = false;
    },
    // 添加角色对话框关闭触发事件
    AddRoleDialogClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.AddRoleVisible = false;
        })
        .catch(() => {
          this.AddRoleVisible = true;
        });
    },
    // 编辑角色对话框关闭按钮
    EditRoleDialogClose() {
      this.$confirm("确认关闭？")
        .then(() => {
          this.EditRoleVisible = false;
        })
        .catch(() => {
          this.EditRoleVisible = true;
        });
    },
    // 点击编辑角色按钮触发事件
    async EditRoleBtn(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) this.$message.error("获取角色数据失败!");
      this.EditRolesList = res.data;
      console.log(this.EditRolesList);
      this.EditRoleVisible = true;
    },
    // 编辑角色对话框确认按钮
    async EditRole(id) {
      const { data: res } = await this.$http.put(
        `roles/${id}`,
        this.EditRolesList
      );
      if (res.meta.status !== 200) this.$message.error("修改角色失败!");
      this.$message.success("修改角色成功!");
      this.getRolesList();
      this.EditRoleVisible = false;
    },
    // 删除角色按钮
    DeleteRoleBtn(id) {
      this.$confirm("确认删除该角色？")
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status !== 200) this.$message.error("删除角色失败!");
          this.$message.success("删除角色成功!");
          this.getRolesList();
        })
        .catch(() => {});
    },
  },
};
</script>

<style>
.el-table {
  font-family: Arial, Helvetica, sans-serif;
}
/* col内元素垂直水平方向居中显示 */
.col_center {
  display: flex;
  justify-content: center;
  align-items: center;
}
/* row内元素垂直方向居中显示 */
.row_center {
  display: flex;
  align-items: center;
}
.bg_top {
  border-top: 1px solid #eee;
}
.bg_bottom {
  border-bottom: 1px solid #eee;
}

.el-tag {
  margin: 7px;
}

/* 底部间距 */
.el-bottom {
  margin-bottom: 20px;
}

.el-breadcrumb{
    font-size: 14px;
}
</style>
